<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="任务名称" prop="nodeName">
        <el-input
          v-model="queryParams.nodeName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="流程状态" prop="flowStatus">
        <el-select v-model="queryParams.flowStatus" placeholder="请选择流程状态" clearable>
          <el-option
            v-for="dict in flow_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          clearable size="small"
          v-model="queryParams.createTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="instanceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed />
      <el-table-column label="序号" width="55" align="center">
        <template #default="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="流程名称" align="center" prop="flowName" :show-overflow-tooltip="true"/>
      <el-table-column label="任务名称" align="center" prop="nodeName" :show-overflow-tooltip="true"/>
      <el-table-column label="审批人" align="center" prop="approver" :show-overflow-tooltip="true"/>
      <el-table-column label="转办人" align="center" prop="transferredBy" :show-overflow-tooltip="true"/>
      <el-table-column label="委派人" align="center" prop="delegate" :show-overflow-tooltip="true"/>
      <el-table-column label="流程状态" align="center" prop="flowStatus" :show-overflow-tooltip="true">
        <template #default="scope">
          <dict-tag :options="flow_status" :value="scope.row.flowStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" :show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" fixed="right" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            type="text"
            @click="handle(scope.row)"
            v-hasPermi="['flow:execute:handle']"
          >办理</el-button>
          <el-button
              type="text"
              @click="transferShow(scope.row)"
              v-hasPermi="['flow:execute:handle']"
          >转办</el-button>
          <el-button
            type="text"
            @click="toFlowImage(scope.row.instanceId)"
          >流程图</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改OA 请假申请对话框 -->
    <el-dialog title="转办" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="权限标识" prop="permissionFlag">
          <el-select v-model="form.permissionFlag" multiple collapse-tags filterable>
            <el-option-group
                v-for="groupOption in groupOptions"
                :key="groupOption.label"
                :label="groupOption.label">
              <el-option
                  v-for="item in groupOption.options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="toTransfer">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <component :is="approve" v-model="businessId" :taskId="taskId"
               :disabled="false" @refresh="getList"></component>
    <el-dialog title="流程图" v-model="flowChart" width="1100">
      <img :src="imgUrl" width="1000" height="500" style="margin:0 auto"/>
    </el-dialog>
  </div>
</template>

<script setup name="Todo">
import { getTaskById, toDoPage, transfer } from "@/api/flow/execute";
import { flowImage } from "@/api/flow/definition";
import {defineAsyncComponent, ref} from "vue";
import {modules} from "@/store/modules/permission";
import {listRole} from "@/api/system/role";
import {listUser} from "@/api/system/user";
import {listDept} from "@/api/system/dept";

const { proxy } = getCurrentInstance();
const { flow_status } = proxy.useDict('flow_status');
const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const instanceList = ref([]);
const showSearch = ref(true);
const imgUrl = ref("");
const flowChart = ref(false);
const approve = ref(null);
const taskId = ref("");
const businessId = ref("");
// 是否显示弹出层
const open = ref(false);
const groupOptions = ref([]);


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    nodeName: null,
    flowStatus: null,
    approver: null,
    createTime: null,
  },
  // 表单校验
  rules: {
    permissionFlag: [
      { required: true, message: "请选择权限标识", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

function getList() {
  loading.value = true;
  toDoPage(queryParams.value).then(response => {
    instanceList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryForm");
  handleQuery();
}
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length!==1
  multiple.value = !selection.length
}
/** 办理按钮操作 */
function handle(row) {
  taskId.value = row.id
  businessId.value = row.businessId
  if (row.fromCustom === 'N' && row.fromPath) {
    // 实际情况是，不同条件对应不同的页面，所以用动态组件
    for (const path in modules) {
      const dir = path.split('views/')[1].split('.vue')[0];
      if (dir === row.fromPath) {
        approve.value =defineAsyncComponent(() => modules[path]());
      }
    }
  }
}
function toFlowImage(instanceId) {
  flowImage(instanceId).then(response => {
    flowChart.value = true
    imgUrl.value = "data:image/gif;base64," + response.data;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
// 表单重置
function reset() {
  form.value = {
    permissionFlag: null,
  };
  proxy.resetForm("form");
}
/** 转办弹框显示按钮操作 */
function transferShow(row) {
  reset();
  taskId.value =row.id
  getTaskById(taskId.value).then(res => {
    form.value.permissionFlag = res.data.permissionFlag.split(",")
  });
  getPermissionFlag();
  open.value = true;
}

/** 转办按钮操作 */
function toTransfer() {
  proxy.$refs["form"].validate(valid => {
    if (valid) {
      transfer(taskId.value, Array.isArray(form.value.permissionFlag)
          ? form.value.permissionFlag.join(',') : form.value.permissionFlag).then(() => {
        proxy.$modal.msgSuccess("转办成功");
        open.value = false;
      })
    }
  });
}

/** 选择角色权限范围触发 */
function getPermissionFlag() {
  listRole().then(response => {
    let groupOption = {
      label: '角色',
      options: response.rows.map(item =>{
            return {
              value: 'role:' + item.roleId,
              label: item.roleName
            }
          }
      )
    }
    groupOptions.value.push(groupOption);
    listUser().then(response => {
      let groupOption = {
        label: '用户',
        options: response.rows.map(item =>{
              return {
                value: 'user:'+ item.userId,
                label: item.nickName
              }
            }
        )
      }
      groupOptions.value.push(groupOption);
      listDept().then(response => {
        let groupOption = {
          label: '部门',
          options: response.data.map(item =>{
                return {
                  value: 'dept:' + item.deptId,
                  label: item.deptName
                }
              }
          )
        }
        groupOptions.value.push(groupOption);
      });
    });
  });
}

getList();
</script>
